<template>
  <div class="media-assets-container">
    <!-- 顶部操作栏 -->
    <div class="top-toolbar">
      <div class="toolbar-left">
        <el-button icon="el-icon-back" @click="goBack">返回</el-button>
        <span class="page-title">编辑源码 - {{ pageInfo.title }}</span>
      </div>
      <div class="toolbar-center">
        <el-radio-group v-model="previewMode" size="small">
          <el-radio-button label="visual">可视化预览</el-radio-button>
          <el-radio-button label="code">源码查看</el-radio-button>
        </el-radio-group>
      </div>
      <div class="toolbar-right">
        <el-button type="success" icon="el-icon-view" @click="previewInNewTab">
          新窗口预览
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-check"
          :disabled="!hasModifiedImages"
          @click="batchReplaceImages"
        >
          保存所有修改
        </el-button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧预览区域 -->
      <div class="content-panel with-sidebar">
        <!-- 可视化预览 -->
        <iframe
          v-show="previewMode === 'visual'"
          ref="previewFrame"
          :srcdoc="currentHtmlContent"
          class="preview-frame"
          @load="onPreviewFrameLoad"
        />

        <!-- 源码视图 -->
        <el-input
          v-show="previewMode === 'code'"
          v-model="currentHtmlContent"
          type="textarea"
          class="code-editor"
          readonly
        />
      </div>

      <!-- 右侧图片列表 -->
      <div class="right-panel">
        <div class="panel-header">
          <h3>图片资源列表 ({{ imageList.length }})</h3>
        </div>
        <div class="image-list">
          <div v-if="imageList.length === 0" class="empty-state">
            <i class="el-icon-picture-outline" style="font-size: 48px; color: #dcdfe6;" />
            <p style="color: #909399; margin-top: 10px;">未找到图片资源</p>
          </div>
          <div v-else class="image-items">
            <el-card
              v-for="(img, index) in imageList"
              :key="index"
              shadow="hover"
              class="image-item"
              :class="{ 'selected': selectedImageIndex === index, 'temporary': img.isTemporary }"
              @click.native="highlightImage(img, index)"
            >
              <div class="item-header">
                <div>
                  <el-tag size="mini" type="info">{{ index + 1 }}</el-tag>
                  <span class="image-type">{{ img.type.toUpperCase() }}</span>
                  <el-tag v-if="img.isTemporary" size="mini" type="warning">临时图片</el-tag>
                </div>
                <!-- 缩略图 -->
                <el-image
                  :src="img.originalSrc"
                  fit="cover"
                  class="thumbnail"
                  :preview-src-list="[img.originalSrc]"
                >
                  <div slot="error" class="image-error">
                    <i class="el-icon-picture-outline" />
                  </div>
                </el-image>
              </div>

              <div class="item-field">
                <div class="field-label">
                  当前路径:
                  <span v-if="img.isTemporary" class="temporary-tag">(临时API)</span>
                </div>
                <el-input
                  v-model="img.originalSrc"
                  size="small"
                  readonly
                  class="field-input"
                />
              </div>

              <div v-if="img.finalSrc" class="item-field">
                <div class="field-label suggested">
                  <i class="el-icon-paperclip" /> 建议路径:
                </div>
                <el-input
                  v-model="img.finalSrc"
                  size="small"
                  readonly
                  class="field-input suggested-input"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-document-copy"
                    size="mini"
                    @click.stop="copyToNewSrc(img)"
                  >
                    使用
                  </el-button>
                </el-input>
              </div>

              <div class="item-field">
                <div class="field-label">新路径:</div>
                <el-input
                  v-model="img.newSrc"
                  size="small"
                  placeholder="输入新的图片URL"
                  class="field-input"
                  @click.stop
                />
              </div>

              <div v-if="img.alt" class="item-alt">
                <span class="alt-label">Alt:</span> {{ img.alt }}
              </div>

              <el-button
                size="mini"
                type="primary"
                :disabled="!img.newSrc || img.newSrc === img.originalSrc"
                @click.stop="replaceImage(img, index)"
              >
                替换此图片
              </el-button>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import { CheckFiles } from '@/api/static_web/page'

export default {
  name: 'MediaAssets',
  data() {
    return {
      pageId: null,
      pageInfo: {
        title: '',
        slug: ''
      },
      currentHtmlContent: '',
      imageList: [],
      previewMode: 'visual', // visual 或 code
      selectedImageIndex: -1,
      previewFrameReady: false
    }
  },
  computed: {
    hasModifiedImages() {
      return this.imageList.some(img => img.newSrc && img.newSrc !== img.originalSrc)
    }
  },
  created() {
    this.pageId = this.$route.params.id || this.$route.query.id
    if (!this.pageId) {
      this.$message.error('缺少页面ID')
      this.goBack()
      return
    }
    this.loadPageData()
  },
  methods: {
    // 加载页面数据
    loadPageData() {
      const loading = this.$loading({
        lock: true,
        text: '正在加载媒体素材...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      // 获取页面信息
      request({
        url: `/static_web/api/page/${this.pageId}/`,
        method: 'get'
      }).then(response => {
        this.pageInfo = response.data

        // 检查HTML文件是否存在
        return CheckFiles(this.pageId)
      }).then(response => {
        const fileStatus = response.data

        if (!fileStatus.html_exists) {
          loading.close()
          this.$message.warning('HTML 文件不存在，请先生成页面')
          this.goBack()
          return
        }

        // 提取图片
        return request({
          url: `/static_web/api/page/${this.pageId}/extract_images/`,
          method: 'get'
        })
      }).then(response => {
        loading.close()
        const data = response.data

        this.currentHtmlContent = data.html_content
        this.imageList = data.images.map(img => ({
          ...img,
          newSrc: img.originalSrc
        }))

        // 等待DOM更新后注入脚本
        this.$nextTick(() => {
          setTimeout(() => {
            this.injectHighlightScript()
          }, 500)
        })
      }).catch(() => {
        loading.close()
        this.$message.error('加载失败')
        this.goBack()
      })
    },
    // 返回
    goBack() {
      this.$router.back()
    },
    // iframe加载完成
    onPreviewFrameLoad() {
      this.previewFrameReady = true
      this.injectHighlightScript()
    },
    // 注入高亮脚本
    injectHighlightScript() {
      try {
        const iframe = this.$refs.previewFrame
        if (!iframe || !iframe.contentWindow) return

        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document

        const style = iframeDoc.createElement('style')
        style.textContent = `
          .media-asset-highlight {
            outline: 3px solid #1890ff !important;
            outline-offset: 2px;
            box-shadow: 0 0 10px rgba(24, 144, 255, 0.5) !important;
            animation: pulse-highlight 1s ease-in-out;
          }
          @keyframes pulse-highlight {
            0%, 100% { outline-color: #1890ff; }
            50% { outline-color: #40a9ff; }
          }
        `
        iframeDoc.head.appendChild(style)
      } catch (e) {
        console.warn('无法注入高亮脚本', e)
      }
    },
    // 高亮图片
    highlightImage(img, index) {
      this.selectedImageIndex = index

      if (this.previewMode !== 'visual') {
        this.previewMode = 'visual'
        this.$nextTick(() => {
          setTimeout(() => this.doHighlightImage(img), 300)
        })
      } else {
        this.doHighlightImage(img)
      }
    },
    // 执行高亮
    doHighlightImage(img) {
      try {
        const iframe = this.$refs.previewFrame
        if (!iframe || !iframe.contentWindow) return

        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document

        const highlighted = iframeDoc.querySelectorAll('.media-asset-highlight')
        highlighted.forEach(el => el.classList.remove('media-asset-highlight'))

        let targetElement = null

        if (img.type === 'img') {
          const images = iframeDoc.querySelectorAll('img')
          for (const imgEl of images) {
            if (imgEl.src === img.originalSrc || imgEl.getAttribute('src') === img.originalSrc) {
              targetElement = imgEl
              break
            }
          }
        } else if (img.type === 'css') {
          const allElements = iframeDoc.querySelectorAll('*')
          for (const el of allElements) {
            const bgImage = window.getComputedStyle(el).backgroundImage
            if (bgImage && bgImage.includes(img.originalSrc)) {
              targetElement = el
              break
            }
          }
        }

        if (targetElement) {
          targetElement.classList.add('media-asset-highlight')
          targetElement.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
          })
          this.$message.success(`已定位到图片 #${this.selectedImageIndex + 1}`)
        } else {
          this.$message.warning('无法在页面中找到该图片元素')
        }
      } catch (e) {
        console.warn('高亮图片失败', e)
      }
    },
    // 复制建议路径
    copyToNewSrc(img) {
      if (img.finalSrc) {
        img.newSrc = img.finalSrc
        this.$message.success('已复制建议路径到新路径')
      }
    },
    // 替换单个图片
    replaceImage(img, index) {
      if (!img.newSrc || img.newSrc === img.originalSrc) {
        this.$message.warning('新路径不能为空或与原路径相同')
        return
      }

      this.$confirm(`确定将图片路径从 "${img.originalSrc}" 替换为 "${img.newSrc}" 吗？`, '确认替换', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在替换图片...',
          spinner: 'el-icon-loading'
        })

        request({
          url: `/static_web/api/page/${this.pageId}/replace_images/`,
          method: 'post',
          data: {
            replacements: [{
              originalSrc: img.originalSrc,
              newSrc: img.newSrc,
              type: img.type
            }]
          }
        }).then(response => {
          loading.close()
          this.$message.success('图片替换成功')
          this.currentHtmlContent = response.data.html_content
          this.imageList[index].originalSrc = img.newSrc
          this.imageList[index].newSrc = img.newSrc
        }).catch(() => {
          loading.close()
          this.$message.error('图片替换失败')
        })
      })
    },
    // 批量替换
    batchReplaceImages() {
      const modifiedImages = this.imageList.filter(img =>
        img.newSrc && img.newSrc !== img.originalSrc
      )

      if (modifiedImages.length === 0) {
        this.$message.warning('没有修改的图片')
        return
      }

      this.$confirm(`确定要批量替换 ${modifiedImages.length} 张图片吗？`, '确认批量替换', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: `正在批量替换 ${modifiedImages.length} 张图片...`,
          spinner: 'el-icon-loading'
        })

        const replacements = modifiedImages.map(img => ({
          originalSrc: img.originalSrc,
          newSrc: img.newSrc,
          type: img.type
        }))

        request({
          url: `/static_web/api/page/${this.pageId}/replace_images/`,
          method: 'post',
          data: { replacements }
        }).then(response => {
          loading.close()
          this.$message.success(`成功替换 ${modifiedImages.length} 张图片`)
          this.currentHtmlContent = response.data.html_content

          modifiedImages.forEach(modImg => {
            const img = this.imageList.find(i => i.originalSrc === modImg.originalSrc)
            if (img) {
              img.originalSrc = modImg.newSrc
              img.newSrc = modImg.newSrc
            }
          })
        }).catch(() => {
          loading.close()
          this.$message.error('批量替换失败')
        })
      })
    },
    // 新窗口预览
    previewInNewTab() {
      CheckFiles(this.pageId).then(response => {
        const fileStatus = response.data
        if (fileStatus.html_exists) {
          const previewUrl = `${process.env.VUE_APP_BASE_API}${fileStatus.html_url}`
          window.open(previewUrl, '_blank')
        } else {
          this.$message.warning('HTML 文件不存在')
        }
      })
    }
  }
}
</script>

<style scoped>
.media-assets-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  z-index: 100;
}

/* 顶部工具栏 */
.top-toolbar {
  height: 60px;
  background: white;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.toolbar-left,
.toolbar-center,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-left: 10px;
}

/* 主内容区 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 内容面板 */
.content-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  margin: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 有侧边栏时的样式 */
.content-panel.with-sidebar {
  margin-right: 10px;
}

.preview-frame,
.code-editor {
  width: 100%;
  height: 100%;
  border: none;
}

.code-editor >>> textarea {
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
  font-size: 13px;
  line-height: 1.6;
}

/* 右侧面板 */
.right-panel {
  width: 450px;
  display: flex;
  flex-direction: column;
  background: white;
  margin: 20px;
  margin-left: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.image-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.image-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 图片项 */
.image-item {
  cursor: pointer;
  transition: all 0.3s;
}

.image-item.selected {
  background-color: #e6f7ff;
  border: 2px solid #1890ff;
}

.image-item.temporary {
  background-color: #fff7e6;
}

.image-item >>> .el-card__body {
  padding: 15px;
}

.item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.image-type {
  margin-left: 8px;
  font-weight: bold;
  font-size: 12px;
}

.thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  font-size: 20px;
  color: #909399;
}

.item-field {
  margin-bottom: 10px;
}

.field-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.field-label.suggested {
  color: #67c23a;
}

.temporary-tag {
  color: #e6a23c;
}

.field-input {
  font-size: 11px;
}

.field-input >>> input,
.field-input >>> textarea {
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
}

.suggested-input >>> input {
  background-color: #f0f9ff;
}

.item-alt {
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.alt-label {
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

/* 滚动条样式 */
.image-list::-webkit-scrollbar {
  width: 6px;
}

.image-list::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.image-list::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style>

